<?php

/**
 * @example
 * $page = new datalist();
 * $page->setQuery('select * from table where a=1');
 * $page->setPagerTemplate('pager_control.tpl');
 * $data = $page->getData();
 * $pages = $page->getPages();
 *
 * @author xydream
 *
 */
class datalist {

    /**
     * 数据库连接标识
     * @var dbresource
     */
    private $link_identifier;
    /**
     * Smartty对象
     * @var Object
     */
    private $smarty;
    /**
     * 数据查询SQL串
     * @var String
     */
    private $querySql;
    /**
     * 数据总数
     * @var Int
     */
    private $totalItem;
    /**
     * 每页数据数
     * @var Int
     */
    private $perPage = 0;
    /**
     * 总页数
     * @var Int
     */
    private $totalPage;
    /**
     * 当前页码
     * @var Int
     */
    private $currentPage;
    /**
     * 上一页页码
     * @var Int
     */
    private $prevPage;
    /**
     * 下一页页码
     * @var Int
     */
    private $nextPage;
    /**
     * 用来构造分页的数组
     * @var Array
     */
    private $arrPage = array();
    /**
     * 当没有分页时(即总条目数不大于每页显示的条目数)是否显示分页栏
     * @var Bool
     */
    private $isShowForSimplePage = true;
    /**
     * URL额外参数
     * @var Array
     */
    private $params = array();
    /**
     * 当前URL地址
     * @var String
     */
    private $url;
    /**
     * URL页码变量名
     * @var String
     */
    private $pageVar = 'page';
    /**
     * 分页样式模板
     * @var String
     */
    private $pagerTemplate;
    /**
     * 当前页数据集
     * @var mixed
     */
    private $data;
    /**
     * 分页结果串
     * @var String
     */
    private $pages;

    /**
     * 构造函数
     */
    public function __construct($sql = '') {
        $this->setLinkIdentifier();
        if (!empty($sql)) {
            $this->setQuery($sql);
        }
    }

    /**
     * 设置页码变量名称
     * @param String $var
     */
    public function setPageVar($var = 'page') {
        $this->pageVar = (string) $var;
        return $this;
    }

    /**
     * 返回页码变量名称
     */
    public function getPageVar() {
        if ($this->pageVar == null) {
            $this->setPageVar();
        }
        return $this->pageVar;
    }

    /**
     * 解析当前URL
     */
    public function getUrl() {
        $queryString = $_SERVER ["QUERY_STRING"];
        parse_str($queryString, $array);
        foreach ($array as $key => $value) {
            if ($key == $this->getPageVar())
                continue;
            else
                $tmp_arr [$key] .= $array [$key];
        }
        if (!empty($this->params)) {
            $tmp_arr = array_merge($tmp_arr, $this->params);
        }
        $tmp_str = http_build_query((array) $tmp_arr);
        $this->url = "http://" . $_SERVER ["HTTP_HOST"] . $_SERVER ["PHP_SELF"];
        if (!empty($tmp_str)) {
            $this->url.="?" . $tmp_str;
        }
        return $this->url;
    }

    /**
     * 设置数据库连接标识
     * @param $link_identifier
     */
    public function setLinkIdentifier($link_identifier = Null) {
        if ($link_identifier === null && isset($GLOBALS['cbdb'])) {
            $this->link_identifier = $GLOBALS['cbdb'];
        } else {
            $this->link_identifier = $link_identifier;
        }
        return $this;
    }

    public function getLinkIdentifier() {
        if ($this->link_identifier === null) {
            $this->setLinkIdentifier();
        }
        return $this->link_identifier;
    }

    /**
     * 设置Smarty对象
     * @param unknown_type $smarty
     */
    public function setSmarty($smarty = NULL) {
        if ($smarty === null && isset($GLOBALS['tpl'])) {
            $this->smarty = $GLOBALS['tpl'];
        } else {
            $this->smarty = $smarty;
        }
        return $this;
    }

    /**
     * 返回Smarty对象
     */
    public function getSmarty() {
        if ($this->smarty === null) {
            $this->setSmarty();
        }
        return $this->smarty;
    }

    /**
     * 设置数据查询SQL
     * @param String $sql
     */
    public function setQuery($sql) {
        $this->querySql = (string) $sql;
        return $this;
    }

    /**
     * 返回数据查询SQL
     */
    public function getQuery() {
        return $this->querySql;
    }

    /**
     * 设置总页数
     */
    public function setTotalPage() {
        if ($this->totalItem === null) {
            $this->setTotalItem();
        }
        $this->totalPage = ceil($this->totalItem / $this->getPerPage());
        return $this;
    }

    /**
     * 返回总页数
     */
    public function getTotalPage() {
        if ($this->totalPage === null) {
            $this->setTotalPage();
        }
        return $this->totalPage;
    }

    /**
     * 设置当前页码
     * @param $page
     */
    public function setCurrentPage($page = 1) {
        $page = intval($page);
        if ($page < 1) {
            $this->currentPage = 1;
        } else {
            $this->currentPage = $page;
        }
    }

    /**
     * 返回当前页码
     */
    public function getCurrentPage() {
        if ($this->currentPage === null) {
            $this->setCurrentPage();
        }
        return $this->currentPage;
    }

    /**
     * 返回上一页页码
     */
    public function getPrevPage() {
        $this->prevPage = $this->getCurrentPage() - 1;
        if ($this->prevPage < 1) {
            $this->prevPage = '';
        }
        return $this->prevPage;
    }

    /**
     * 返回下一页页码
     */
    public function getNextPage() {
        $this->nextPage = $this->getCurrentPage() + 1;
        if ($this->nextPage > $this->getTotalPage()) {
            $this->nextPage = '';
        }
        return $this->nextPage;
    }

    /**
     * 设置（统计）数据总数
     * @param Int $totalItem 数据总数
     */
    public function setTotalItem($totalItem = null) {
        if ($totalItem) {
            $this->totalItem = intval($totalItem);
        }
        if ($this->totalItem === null) {
            $countQuery = eregi_replace("select[ \r\n\t](.*)[ \r\n\t]from", "Select count(*) as citybao_count From", $this->getQuery());
            $countQuery = eregi_replace('order[ \r\n\t]{1,}by(.*)', '', $countQuery);
            $row = $this->getLinkIdentifier()->get_row($countQuery, ARRAY_A);
            if (is_array($row)) {
                $this->totalItem = $row ['citybao_count'];
            } else {
                $this->totalItem = 0;
            }
        }
        $this->setTotalPage();
        return $this;
    }

    /**
     * 返回数据总数
     */
    public function getTotalItem() {
        if ($this->totalItem === null) {
            $this->setTotalItem();
        }
        return $this->totalItem;
    }

    /**
     * 设置每页显示数据条数
     * @param int $perPage
     */
    public function setPerPage($perPage = null) {
        global $config_core;
        if (!$perPage) {
            $this->perPage = intval($config_core['page_data_num']);
        } else {
            $this->perPage = intval($perPage);
        }
        return $this;
    }

    /**
     * 返回每页显示数据条数
     */
    public function getPerPage() {
        if(!$this->perPage){
            $this->setPerPage();
        }
        return $this->perPage;
    }

    /**
     * 返回起始记录位置
     */
    public function getStartPos() {
        return ($this->getCurrentPage() - 1) * $this->getPerPage();
    }

    /**
     * 设置当没有分页时(即总条目数不大于每页显示的条目数)是否显示分页栏
     * @param $isShow
     */
    public function setIsShowForSimplePage($isShow = true) {
        $this->isShowForSimplePage = $isShow;
        return $this;
    }

    /**
     * 设置分页样式模板
     * @param String $template
     */
    public function setPagerTemplate($template = 'pager_control.tpl') {
        $this->pagerTemplate = (string) $template;
    }

    /**
     * 构建并返回分页显示的页码
     */
    public function getArrPage() {
        $this->arrPage = array();
        if ($this->getTotalPage() < 11) {
            for ($i = 1; $i <= $this->getTotalPage(); $i++) {
                $this->arrPage[] = $i;
            }
        } else {
            if ($this->getCurrentPage() <= 6) {
                for ($i = 1; $i <= $this->getCurrentPage(); $i++) {
                    $this->arrPage[] = $i;
                }
            } else {
                for ($i = $this->getCurrentPage() - 5; $i <= $this->getCurrentPage(); $i++) {
                    $this->arrPage[] = $i;
                }
            }
            if ($this->getTotalPage() - $this->getCurrentPage() < 5) {
                for ($i = $this->getCurrentPage() + 1; $i <= getTotalPage(); $i++) {
                    $this->arrPage[] = $i;
                }
            } else {
                for ($i = $this->getCurrentPage() + 1; $i <= $this->getCurrentPage() + 5; $i++) {
                    $this->arrPage[] = $i;
                }
            }
        }
        return $this->arrPage;
    }

    /**
     * 获取页码链接
     * @param $page
     */
    public function getPageLink($page) {
        $symbol = '&';
        if (strpos($this->getUrl(), '?') === false) {
            $symbol = '?';
        }
        return $this->getUrl() . $symbol . $this->getPageVar() . '=' . $page;
    }

    /**
     * 获取数据集
     */
    public function getData() {
        if ($this->data) {
            return $this->data;
        }
        $querySql = $this->querySql . ' LIMIT ' . $this->getStartPos() . ',' . $this->getPerPage();
        $this->data = $this->getLinkIdentifier()->get_results($querySql);
        return $this->data;
    }

    /**
     * 获取分页结果串
     * @param String $template
     */
    public function getPages($template = null) {
        if ($this->pages === null) {
            if ($template) {
                $this->setPagerTemplate($template);
            }
            if ($this->pagerTemplate == null) {
                $this->setPagerTemplate();
            }
            $this->getSmarty()->assign('page', $this);
            if ($this->getTotalPage() == 1 && !$this->isShowForSimplePage) {
                $this->pages = '';
            } else {
                $this->pages = $this->getSmarty()->fetch($this->pagerTemplate);
            }
        }
        return $this->pages;
    }

}